package lee.vioson.ebook.viewmodels

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import lee.vioson.composecommon.base.mvi.BaseViewModel
import lee.vioson.composecommon.base.mvi.Reducer
import lee.vioson.composecommon.base.mvi.UiEvent
import lee.vioson.composecommon.base.mvi.UiState
import lee.vioson.ebook.data.AppContainer
import lee.vioson.ebook.data.pagedata.pageDataSource
import lee.vioson.remotedata.bean.Book

/**
 *Author:viosonlee
 *Date:2023/6/16
 *DESCRIPTION:
 */
class RecentlyViewModel(private val appContainer: AppContainer) :
    AppViewModel<RecentlyViewModel.State, RecentlyViewModel.Event>(appContainer.appEvent) {

    private val reducer = SubReducer(State())

    override val state: StateFlow<State>
        get() = reducer.state

    override fun sendEvent(event: Event) {
        reducer.sendEvent(event)
    }

    fun fetchRecentlyList() =
        appContainer.homeRepository.fetchRecentlyBooks()
            .catch { handleException(it) }
            .onEach { sendEvent(Event.OnRecentlyList(it)) }
            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
            .launchIn(viewModelScope)

    val recommendPageData =
        pageDataSource { appContainer.homeRepository.recommendBookList(appContainer.uniqueId, it) }

    private class SubReducer(initialState: State) :
        Reducer<State, Event>(initialState) {
        override fun reduce(oldState: State, event: Event) {
            when (event) {
                is Event.OnRecentlyList -> setState(oldState.copy(recentlyList = event.recentlyList))
            }
        }
    }


    sealed class Event : UiEvent {
        data class OnRecentlyList(val recentlyList: List<Book>):Event()
    }

    data class State(
        val isVip: Boolean = false,
        val recentlyList:List<Book> = emptyList(),
    ) : UiState
}

